package com.healthdata.controller;

import com.healthdata.entity.User;
import com.healthdata.entity.UserApplication;
import com.healthdata.service.UserService;
import com.healthdata.util.JwtUtil;
import com.healthdata.vo.UserApplicationVO;
import com.healthdata.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auditor")
@PreAuthorize("hasAuthority('AUDITOR')")
public class AuditorController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    // 审核员只能查看研究员列表
    @GetMapping("/users")
    public List<UserVO> getAllResearchers() {
        return userService.list().stream()
                .filter(user -> User.ROLE_RESEARCHER.equals(user.getRole()))
                .map(this::convertToUserVO)
                .collect(Collectors.toList());
    }

    // 审核员查看研究员详情（限制只能查看研究员）
    @GetMapping("/users/{userId}")
    public Map<String, Object> getResearcherById(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.getById(userId);

        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }

        if (!User.ROLE_RESEARCHER.equals(user.getRole())) {
            result.put("success", false);
            result.put("message", "无权查看非研究员用户");
            return result;
        }

        result.put("success", true);
        result.put("user", convertToUserVO(user));
        return result;
    }

    // 审核员修改研究员信息（限制只能修改研究员）
    @PutMapping("/users/{userId}")
    public Map<String, Object> updateResearcher(
            @PathVariable Long userId,
            @RequestBody User userUpdateRequest,
            @RequestHeader("Authorization") String token
    ) {
        Map<String, Object> result = new HashMap<>();
        User userToUpdate = userService.getById(userId);

        if (userToUpdate == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }

        if (!User.ROLE_RESEARCHER.equals(userToUpdate.getRole())) {
            result.put("success", false);
            result.put("message", "无权修改非研究员用户");
            return result;
        }

        // 限制审核员不能修改角色
        userUpdateRequest.setRole(userToUpdate.getRole());

        // 其他字段更新逻辑...
        if (userUpdateRequest.getUsername() != null) {
            userToUpdate.setUsername(userUpdateRequest.getUsername());
        }
        if (userUpdateRequest.getPassword() != null) {
            userToUpdate.setPassword(userUpdateRequest.getPassword());
        }
        if (userUpdateRequest.getEmail() != null) {
            userToUpdate.setEmail(userUpdateRequest.getEmail());
        }
        if (userUpdateRequest.getPhone() != null) {
            userToUpdate.setPhone(userUpdateRequest.getPhone());
        }
        if (userUpdateRequest.getStatus() != null) {
            userToUpdate.setStatus(userUpdateRequest.getStatus());
        }

        boolean success = userService.updateById(userToUpdate);
        result.put("success", success);
        result.put("message", success ? "用户信息更新成功" : "用户信息更新失败");
        return result;
    }

    // 审核员删除用户接口（仅能删除研究员）
    @DeleteMapping("/users/{userId}")
    public Map<String, Object> deleteResearcher(@PathVariable Long userId, @RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();

        // 验证当前用户是否为审核员
        Long auditorId = jwtUtil.getUserIdFromToken(token);
        if (auditorId == null) {
            result.put("success", false);
            result.put("message", "Token 无效");
            return result;
        }

        // 检查目标用户是否存在
        User targetUser = userService.getById(userId);
        if (targetUser == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }

        // 检查目标用户是否为研究员
        if (!User.ROLE_RESEARCHER.equals(targetUser.getRole())) {
            result.put("success", false);
            result.put("message", "审核员只能删除研究员用户");
            return result;
        }

        // 执行删除操作
        boolean success = userService.removeById(userId);
        result.put("success", success);
        result.put("message", success ? "用户删除成功" : "用户删除失败");
        return result;
    }

    private UserVO convertToUserVO(User user) {
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setPassword(user.getPassword());
        userVO.setRole(user.getRole());
        userVO.setEmail(user.getEmail());
        userVO.setPhone(user.getPhone());
        userVO.setStatus(user.getStatus());
        userVO.setCreateTime(user.getCreateTime());
        userVO.setUpdateTime(user.getUpdateTime());
        return userVO;
    }

    // 获取所有审核员待处理的申请列表
    @GetMapping("/applications")
    public List<UserApplicationVO> getAllApplications() {
        return userService.getAllAuditorApplications();
    }

    // 处理申请
    @PostMapping("/handleApplication")
    public Map<String, Object> handleApplication(@RequestBody Map<String, Object> handleInfo) {
        Map<String, Object> result = new HashMap<>();
        // 添加空值检查
        if (handleInfo.get("applicationId") == null || handleInfo.get("isApproved") == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数，请提供申请ID、审批结果");
            return result;
        }
        Long applicationId = Long.valueOf(handleInfo.get("applicationId").toString());
        boolean isApproved = (boolean) handleInfo.get("isApproved");
        String reply = (String) handleInfo.get("reply"); // 获取审核员回复消息

        UserApplication application = userService.getApplicationById(applicationId);
        if (application != null && "AUDITOR".equals(application.getTargetRole()) && application.getStatus().startsWith("未处理")) {
            application.setHandleTime(new Date());
            if (isApproved) {
                application.setStatus("已处理");
            } else {
                application.setStatus("拒绝");
            }
            if (reply != null) {
                application.setAdminReply(reply); // 设置审核员回复消息
            }
            boolean success = userService.updateApplication(application);
            result.put("success", success);
            result.put("message", success ? "申请处理成功" : "申请处理失败");
        } else {
            if (!application.getStatus().startsWith("未处理")){
                result.put("success", false);
                result.put("message", "该申请已处理，请勿重复操作");
            }else {
                result.put("success", false);
                result.put("message", "该申请不是反馈给审核员的申请");
            }
        }
        return result;
    }

    // 审核员向管理员反馈，发送消息
    @PostMapping("/sendApplication")
    public Map<String, Object> applyToAdmin(@RequestBody Map<String, String> applyInfo, @RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId != null) {
            String reason = applyInfo.get("reason");
            String targetRole = "ADMIN";

            UserApplication application = new UserApplication();
            application.setUserId(userId);
            application.setReason(reason);
            application.setStatus("未处理");
            application.setTargetRole(targetRole);

            boolean success = userService.submitApplication(application);
            result.put("success", success);
            result.put("message", success ? "反馈提交成功" : "反馈提交失败");
        } else {
            result.put("success", false);
            result.put("message", "Token 无效");
        }
        return result;
    }

    // 审核员查看自己的申请进度
    @GetMapping("/checkSelfApplicationStatus")
    public Map<String, Object> checkSelfApplicationStatus(@RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId != null) {
            List<UserApplicationVO> applicationVOs = userService.getUserApplication(userId);
            if (!applicationVOs.isEmpty()) {
                result.put("success", true);
                result.put("applications", applicationVOs);
            } else {
                result.put("success", true);
                result.put("message", "没有申请信息");
            }
        } else {
            result.put("success", false);
            result.put("message", "Token 无效");
        }
        return result;
    }
}
